{
 "cells": [
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2025-01-17T12:14:04.168288Z",
     "start_time": "2025-01-17T12:14:04.161277Z"
    }
   },
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "# 分组后给名称加前缀\n",
    "dict_obj = {'key1' : ['a', 'b', 'a', 'b',\n",
    "                      'a', 'b', 'a', 'a'],\n",
    "            'key2' : ['one', 'one', 'two', 'three',\n",
    "                      'two', 'two', 'one', 'three'],\n",
    "            'data1': np.random.randint(1, 10, 8),\n",
    "            'data2': np.random.randint(1, 10, 8)}\n",
    "df_obj = pd.DataFrame(dict_obj)\n",
    "print(df_obj)\n",
    "print('-'*50)\n",
    "# 按key1分组后，计算data1，data2的统计信息并附加到原始表格中，并添加表头前缀\n",
    "# numeric_only=True表示只计算数值型数据; add_prefix添加表头前缀\n",
    "k1_sum = df_obj.groupby('key1').mean(numeric_only=True).add_prefix('mean_')\n",
    "print(k1_sum)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  key1   key2  data1  data2\n",
      "0    a    one      7      4\n",
      "1    b    one      9      1\n",
      "2    a    two      3      6\n",
      "3    b  three      8      4\n",
      "4    a    two      5      6\n",
      "5    b    two      7      3\n",
      "6    a    one      7      6\n",
      "7    a  three      5      4\n",
      "--------------------------------------------------\n",
      "      mean_data1  mean_data2\n",
      "key1                        \n",
      "a            5.4    5.200000\n",
      "b            8.0    2.666667\n"
     ]
    }
   ],
   "execution_count": 11
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-17T12:14:04.525513Z",
     "start_time": "2025-01-17T12:14:04.519246Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 方法2，使用transform，分组后计算结果和原本的df保持一致\n",
    "# 存在非数值型列，先把数值型挑出来\n",
    "k1_sum_tf = df_obj.loc[:, ['key1','data1', 'data2']].groupby('key1').transform('mean').add_prefix('mean_')\n",
    "print(k1_sum_tf)\n",
    "# 将计算得到的平均值数据框k1_sum_tf的列附加到原始数据框 df_obj 中。\n",
    "df_obj[k1_sum_tf.columns] = k1_sum_tf\n",
    "print(df_obj)"
   ],
   "id": "7a41b2a0943112aa",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   mean_data1  mean_data2\n",
      "0         5.4    5.200000\n",
      "1         8.0    2.666667\n",
      "2         5.4    5.200000\n",
      "3         8.0    2.666667\n",
      "4         5.4    5.200000\n",
      "5         8.0    2.666667\n",
      "6         5.4    5.200000\n",
      "7         5.4    5.200000\n",
      "  key1   key2  data1  data2  mean_data1  mean_data2\n",
      "0    a    one      7      4         5.4    5.200000\n",
      "1    b    one      9      1         8.0    2.666667\n",
      "2    a    two      3      6         5.4    5.200000\n",
      "3    b  three      8      4         8.0    2.666667\n",
      "4    a    two      5      6         5.4    5.200000\n",
      "5    b    two      7      3         8.0    2.666667\n",
      "6    a    one      7      6         5.4    5.200000\n",
      "7    a  three      5      4         5.4    5.200000\n"
     ]
    }
   ],
   "execution_count": 12
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-17T12:14:05.322198Z",
     "start_time": "2025-01-17T12:14:05.315704Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 删除key2列\n",
    "df_obj.drop(['key2'], axis=1, inplace=True)\n",
    "print('-'*50)\n",
    "print(df_obj)"
   ],
   "id": "39f0bba56a77ecf8",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "--------------------------------------------------\n",
      "  key1  data1  data2  mean_data1  mean_data2\n",
      "0    a      7      4         5.4    5.200000\n",
      "1    b      9      1         8.0    2.666667\n",
      "2    a      3      6         5.4    5.200000\n",
      "3    b      8      4         8.0    2.666667\n",
      "4    a      5      6         5.4    5.200000\n",
      "5    b      7      3         8.0    2.666667\n",
      "6    a      7      6         5.4    5.200000\n",
      "7    a      5      4         5.4    5.200000\n"
     ]
    }
   ],
   "execution_count": 13
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-17T12:14:06.494414Z",
     "start_time": "2025-01-17T12:14:06.483715Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#实现a组和b组，谁比平均分高，谁比平均分低\n",
    "def diff_mean(s):\n",
    "    \"\"\"\n",
    "        返回数据与均值的差值，s传入的是某一个分组\n",
    "    \"\"\"\n",
    "    return s - s.mean()\n",
    "\n",
    "print(df_obj.groupby('key1').transform(diff_mean))\n",
    "df_obj"
   ],
   "id": "64ff8466d4a75a0a",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   data1     data2  mean_data1  mean_data2\n",
      "0    1.6 -1.200000         0.0         0.0\n",
      "1    1.0 -1.666667         0.0         0.0\n",
      "2   -2.4  0.800000         0.0         0.0\n",
      "3    0.0  1.333333         0.0         0.0\n",
      "4   -0.4  0.800000         0.0         0.0\n",
      "5   -1.0  0.333333         0.0         0.0\n",
      "6    1.6  0.800000         0.0         0.0\n",
      "7   -0.4 -1.200000         0.0         0.0\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "  key1  data1  data2  mean_data1  mean_data2\n",
       "0    a      7      4         5.4    5.200000\n",
       "1    b      9      1         8.0    2.666667\n",
       "2    a      3      6         5.4    5.200000\n",
       "3    b      8      4         8.0    2.666667\n",
       "4    a      5      6         5.4    5.200000\n",
       "5    b      7      3         8.0    2.666667\n",
       "6    a      7      6         5.4    5.200000\n",
       "7    a      5      4         5.4    5.200000"
      ],
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>key1</th>\n",
       "      <th>data1</th>\n",
       "      <th>data2</th>\n",
       "      <th>mean_data1</th>\n",
       "      <th>mean_data2</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>a</td>\n",
       "      <td>7</td>\n",
       "      <td>4</td>\n",
       "      <td>5.4</td>\n",
       "      <td>5.200000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>b</td>\n",
       "      <td>9</td>\n",
       "      <td>1</td>\n",
       "      <td>8.0</td>\n",
       "      <td>2.666667</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>a</td>\n",
       "      <td>3</td>\n",
       "      <td>6</td>\n",
       "      <td>5.4</td>\n",
       "      <td>5.200000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>b</td>\n",
       "      <td>8</td>\n",
       "      <td>4</td>\n",
       "      <td>8.0</td>\n",
       "      <td>2.666667</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>a</td>\n",
       "      <td>5</td>\n",
       "      <td>6</td>\n",
       "      <td>5.4</td>\n",
       "      <td>5.200000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>b</td>\n",
       "      <td>7</td>\n",
       "      <td>3</td>\n",
       "      <td>8.0</td>\n",
       "      <td>2.666667</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>a</td>\n",
       "      <td>7</td>\n",
       "      <td>6</td>\n",
       "      <td>5.4</td>\n",
       "      <td>5.200000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>a</td>\n",
       "      <td>5</td>\n",
       "      <td>4</td>\n",
       "      <td>5.4</td>\n",
       "      <td>5.200000</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 14
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": "",
   "id": "19d400dc95da1211"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
